#include "../include/department_handler.h"
#include "../include/db_manager.h"
#include <jsoncpp/json/json.h>
#include <iostream>

std::string DepartmentHandler::getAllDepartments() {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "SELECT * FROM departments ORDER BY Dno";
    auto results = db.executeSelectQuery(query);
    
    Json::Value response;
    response["success"] = true;
    response["data"] = Json::Value(Json::arrayValue);
    
    for (const auto& row : results) {
        Json::Value department;
        department["id"] = row.at("Dno");
        department["name"] = row.at("Dname");
        department["manager"] = row.at("Dmanger");
        department["phone"] = row.at("Dphone");
        department["email"] = row.at("Demail");
        department["address"] = row.at("Daddress");
        department["budget"] = row.at("money");
        
        response["data"].append(department);
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string DepartmentHandler::getDepartmentById(const std::string& id) {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "SELECT * FROM departments WHERE Dno = '" + db.escapeString(id) + "'";
    auto results = db.executeSelectQuery(query);
    
    Json::Value response;
    if (results.empty()) {
        response["success"] = false;
        response["message"] = "部门不存在";
    } else {
        response["success"] = true;
        const auto& row = results[0];
        
        Json::Value department;
        department["id"] = row.at("Dno");
        department["name"] = row.at("Dname");
        department["manager"] = row.at("Dmanger");
        department["phone"] = row.at("Dphone");
        department["email"] = row.at("Demail");
        department["address"] = row.at("Daddress");
        department["budget"] = row.at("money");
        
        response["data"] = department;
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string DepartmentHandler::addDepartment(const std::string& data) {
    Json::Value request_data;
    Json::Reader reader;
    
    if (!reader.parse(data, request_data)) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "数据格式错误";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = "INSERT INTO departments (Dno, Dname, Dmanger, Dphone, Demail, Daddress, money) VALUES ('" +
                       db.escapeString(request_data["id"].asString()) + "', '" +
                       db.escapeString(request_data["name"].asString()) + "', '" +
                       db.escapeString(request_data["manager"].asString()) + "', '" +
                       db.escapeString(request_data["phone"].asString()) + "', '" +
                       db.escapeString(request_data["email"].asString()) + "', '" +
                       db.escapeString(request_data["address"].asString()) + "', " +
                       request_data["budget"].asString() + ")";
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "部门添加成功";
    } else {
        response["success"] = false;
        response["message"] = "部门添加失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string DepartmentHandler::updateDepartment(const std::string& id, const std::string& data) {
    Json::Value request_data;
    Json::Reader reader;
    
    if (!reader.parse(data, request_data)) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "数据格式错误";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = std::string("UPDATE departments SET ") +
                       "Dname = '" + db.escapeString(request_data["name"].asString()) + "', " +
                       "Dmanger = '" + db.escapeString(request_data["manager"].asString()) + "', " +
                       "Dphone = '" + db.escapeString(request_data["phone"].asString()) + "', " +
                       "Demail = '" + db.escapeString(request_data["email"].asString()) + "', " +
                       "Daddress = '" + db.escapeString(request_data["address"].asString()) + "', " +
                       "money = " + request_data["budget"].asString() + " " +
                       "WHERE Dno = '" + db.escapeString(id) + "'";
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "部门信息更新成功";
    } else {
        response["success"] = false;
        response["message"] = "部门信息更新失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string DepartmentHandler::deleteDepartment(const std::string& id) {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "DELETE FROM departments WHERE Dno = '" + db.escapeString(id) + "'";
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "部门删除成功";
    } else {
        response["success"] = false;
        response["message"] = "部门删除失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string DepartmentHandler::getDepartmentStatistics() {
    DBManager& db = DBManager::getInstance();
    
    // 总部门数
    auto total_results = db.executeSelectQuery("SELECT COUNT(*) as total FROM departments");
    int total_departments = total_results.empty() ? 0 : std::stoi(total_results[0].at("total"));
    
    // 部门员工统计
    auto emp_results = db.executeSelectQuery("SELECT Dno, COUNT(*) as employee_count FROM employees GROUP BY Dno");
    
    Json::Value response;
    response["success"] = true;
    response["total_departments"] = total_departments;
    response["department_employee_stats"] = Json::Value(Json::arrayValue);
    
    for (const auto& row : emp_results) {
        Json::Value dept_stat;
        dept_stat["department_id"] = row.at("Dno");
        dept_stat["employee_count"] = std::stoi(row.at("employee_count"));
        response["department_employee_stats"].append(dept_stat);
    }
    
    Json::FastWriter writer;
    return writer.write(response);
} 